package com.company.loganalyzer.controller;

import com.company.loganalyzer.config.AgentConfig;
import com.company.loganalyzer.config.ElasticsearchConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 
 * 提供应用健康状态检查和基本信息
 */
@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class HealthController implements HealthIndicator {

    private final ElasticsearchOperations elasticsearchOperations;
    private final AgentConfig agentConfig;
    private final ElasticsearchConfig elasticsearchConfig;

    /**
     * 应用信息端点
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("name", agentConfig.getName());
        info.put("description", agentConfig.getDescription());
        info.put("version", "2.0.0");
        info.put("timestamp", LocalDateTime.now());
        
        // 配置信息
        Map<String, Object> config = new HashMap<>();
        config.put("elasticsearch", Map.of(
            "hosts", elasticsearchConfig.getHosts(),
            "indexPattern", elasticsearchConfig.getIndexPattern(),
            "pageSize", elasticsearchConfig.getPageSize()
        ));
        config.put("agent", Map.of(
            "outputFormat", agentConfig.getOutputFormat(),
            "defaultTimeRange", agentConfig.getDefaultTimeRange(),
            "maxLogLimit", agentConfig.getMaxLogLimit()
        ));
        info.put("config", config);
        
        return ResponseEntity.ok(info);
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> getHealth() {
        Health health = health();
        Map<String, Object> response = new HashMap<>();
        response.put("status", health.getStatus().getCode());
        response.put("details", health.getDetails());
        response.put("timestamp", LocalDateTime.now());
        
        if (health.getStatus().getCode().equals("UP")) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(503).body(response);
        }
    }

    /**
     * Spring Boot Actuator 健康检查
     */
    @Override
    public Health health() {
        try {
            // 检查ElasticSearch连接
            boolean esHealthy = checkElasticsearchHealth();
            
            if (esHealthy) {
                return Health.up()
                    .withDetail("elasticsearch", "UP")
                    .withDetail("agent", "READY")
                    .withDetail("timestamp", LocalDateTime.now())
                    .build();
            } else {
                return Health.down()
                    .withDetail("elasticsearch", "DOWN")
                    .withDetail("agent", "NOT_READY")
                    .withDetail("timestamp", LocalDateTime.now())
                    .build();
            }
        } catch (Exception e) {
            return Health.down()
                .withDetail("error", e.getMessage())
                .withDetail("timestamp", LocalDateTime.now())
                .build();
        }
    }

    /**
     * 检查ElasticSearch健康状态
     */
    private boolean checkElasticsearchHealth() {
        try {
            // 执行一个简单的cluster health检查
            return elasticsearchOperations.indexOps(elasticsearchConfig.getIndexPattern()).exists();
        } catch (Exception e) {
            return false;
        }
    }
}